package com.ljh.mall.controller;

import com.alibaba.fastjson.JSON;
import com.ljh.common.constant.AuthConstant;
import com.ljh.common.constant.SMSConstant;
import com.ljh.common.exception.BizCodeEnume;
import com.ljh.common.utils.R;
import com.ljh.common.vo.MemberVO;
import com.ljh.mall.feign.MemberFeginService;
import com.ljh.mall.feign.ThirdPartFeginService;
import com.ljh.mall.vo.LoginVo;
import com.ljh.mall.vo.UserRegisterVo;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author ：刘剑鸿
 * @date ：Created in 2023/3/27 23:50
 * @description：
 * @modified By：
 * @version: $
 */
@Controller
public class LoginController {
    @Autowired
    private ThirdPartFeginService thirdPartFeginService;

    @Autowired
    private MemberFeginService memberFeginService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/login.html")
    public String login(){
        return "login";
    }

    @GetMapping("/reg.html")
    public String reg(){
        return "reg";
    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone){
        Object o = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if (o != null){
            String s = o.toString();
            if(!"".equals(s)){
                Long l = Long.parseLong(o.toString().split("_")[1]);
                if (System.currentTimeMillis() - l <= 60000){
                    // 说明验证码的发送间隔不足一分钟 提示
                    return R.error(BizCodeEnume.VALID_SMS_EXCEPTION.getCode(),BizCodeEnume.VALID_SMS_EXCEPTION.getMsg());
                }
            }
        }

        //String code = UUID.randomUUID().toString().substring(0,5);
        Integer i = (int)((Math.random()*9+1)*10000);
        String code = i.toString();
        System.out.println("phone"+phone);
        thirdPartFeginService.sendSmsCode(phone,code);
        System.out.println("code"+code);
        code = code + "_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX+phone,code,10, TimeUnit.MINUTES);

        return R.ok();
    }
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        System.out.println("UserRegisterVo==="+ JSON.toJSONString(vo));
        Map<String,String> map = new HashMap<>();
        if (result.hasErrors()){
            // 表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/reg";
        } else {
            // 验证码是否正确
            String code = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            code = code.split("_")[0];
            System.out.println("验证码=="+code);
            if (!code.equals(vo.getCode())){
                System.out.println(1111);
                // 说明验证码不正确
                map.put("code","验证码错误");
                model.addAttribute("error",map);
                return "/reg";
            } else {
                System.out.println(222);
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                R r = memberFeginService.register(vo);
                System.out.println("R返回"+JSON.toJSONString(r));
                if(r.getCode() == 0){
                    // 注册成功
                    return "redirect:http://localhost:30000/login.html";
                }else{
                    // 注册失败
                    map.put("msg",r.getCode()+":"+r.get("msg"));
                    model.addAttribute("error",map);
                    return "/reg";
                }
            }
        }
    }

    @PostMapping("/login")
    public String login(LoginVo loginVo , HttpSession session){
        R r = memberFeginService.login(loginVo);
        if(r.getCode() == 0){
            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);

            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            System.out.println("session的"+JSON.toJSONString(session));
            redisTemplate.opsForValue().set("session",JSON.toJSONString(session));
            // 表示登录成功
            return "redirect:http://localhost:8040/home";
        }

        session.setAttribute("errors",r.get("msg"));

        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://localhost:30000/login.html";


    }
}
